package com.edu.service.impl;

import com.edu.entity.BuyerAddress;
import com.edu.form.AddressForm;
import com.edu.repository.BuyerAddressRepository;
import com.edu.service.AddressService;
import com.edu.vo.AddressVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private BuyerAddressRepository addressRepository;

    @Override
    public List<AddressVO> findAll() {
        List<BuyerAddress> addressList = addressRepository.findAll();
        List<AddressVO> list = addressList.stream().map(e -> new AddressVO(e.getAddressId(), e.getAreaCode(), e.getBuyerName(), e.getBuyerPhone(), e.getBuyerAddress())).collect(Collectors.toList());

        return list;
    }

    @Override
    public void saveOrUpdate(AddressForm addressForm) {
        BuyerAddress buyerAddress;
        if (addressForm.getId() == null) {
            buyerAddress = new BuyerAddress();
        } else {
            buyerAddress = addressRepository.findById(addressForm.getId()).get();

        }
        buyerAddress.setBuyerName(addressForm.getName());
        buyerAddress.setBuyerPhone(addressForm.getTel());
        StringBuffer address = new StringBuffer();
        address.append(addressForm.getProvince()).append(addressForm.getCity()).append(addressForm.getCounty()).append(addressForm.getAddressDetail());
        buyerAddress.setBuyerAddress(address.toString());
        buyerAddress.setAreaCode(addressForm.getAreaCode());
        addressRepository.save(buyerAddress);

    }

}
